﻿using Core.Factory;
using EntityFramework;
using Model;
using NLog;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Commons;

namespace Core.Service
{
    public class ActivityService : IActivityService
    {
        private readonly Logger Logger = LogManager.GetCurrentClassLogger();
        private readonly IUserService _userService;
        private readonly MyDbContext _myDbContext;
        public ActivityService(MyDbContext myDbContext, IUserService userService)
        {
            _myDbContext = myDbContext;
            _userService = userService;
        }

        public T_Activity Add(T_Activity activity, List<T_ActivityDetail> details, List<T_Graphic> graphics, string formId)
        {
            var user = _myDbContext.T_User.FirstOrDefault(i => i.Id == activity.UserId);

            _myDbContext.Database.BeginTransaction();
            activity.CreateDate = DateTime.Now;
            activity.IsOpen = 0;
            activity.ExpireDate = user.ExpireDate;

            activity.CoverPage = "/images/default.png";
            T_Activity model = _myDbContext.T_Activity.Add(activity).Entity;

            _myDbContext.SaveChanges();
            foreach (var item in details)
            {
                item.ActivityId = model.Id;
                item.CreateDate = DateTime.Now;
                _myDbContext.T_ActivityDetail.Add(item);
            }

            T_Form t_Form = new T_Form();
            t_Form.CreateTime = DateTime.Now;
            t_Form.Flag = "Publish";
            t_Form.FormID = formId;
            t_Form.IsValid = 1;
            t_Form.UserId = activity.UserId;
            _myDbContext.T_Form.Add(t_Form);

            T_PointsDetail t_Points = new T_PointsDetail();
            t_Points.UserId = activity.UserId;
            t_Points.PointsRule = PointsRule.PUBLISH.ToString();
            _userService.AddPoints(t_Points);

            if (activity.Points>0) {
                T_PointsDetail p = new T_PointsDetail();
                p.CreateDate = DateTime.Now;
                p.Points = activity.Points * -1;
                p.PointsRule = "通过发布消费积分";
                p.UserId = activity.UserId;
                _myDbContext.T_PointsDetail.Add(p);
                user.Points = user.Points - activity.Points;

            }

            foreach (var item in graphics)
            {
                item.ActivityId = model.Id;
                item.CreateDate = DateTime.Now;
                _myDbContext.T_Graphic.Add(item);
            }

            _myDbContext.SaveChanges();
            _myDbContext.Database.CommitTransaction();
            return model;
        }

        public string GetFormId(int userId,string flag)
        {
            var model = _myDbContext.T_Form.Where(i => i.IsValid != 0&& i.UserId==userId && (DateTime.Now - i.CreateTime).Days < 7&&i.Flag== flag).First();

            model.IsValid = 0;
            _myDbContext.SaveChanges();
            return model.FormID;
        }
        public string SetFormId(string  formId)
        {
            var model = _myDbContext.T_Form.Where(i => i.FormID==formId).First();

            model.IsValid = 0;
            _myDbContext.SaveChanges();
            return model.FormID;
        }
        public T_Activity JoinActivity(T_Join join, string formId)
        {
            var model = _myDbContext.T_Activity.SingleOrDefault(i => i.Id == join.ActivityId);
            if (model != null)
            {

                var oldJoin = _myDbContext.T_Join.SingleOrDefault(i => i.ActivityId == join.ActivityId && i.UserId == join.UserId);
                if (oldJoin != null)
                {
                    throw new Exception("已参加活动");

                }
                

                join.ExchangeCode = GetExchangeCode();
                join.IsLucky = 0;
                join.CreateDate = DateTime.Now;
                _myDbContext.T_Join.Add(join);

                T_Form t_Form = new T_Form();
                t_Form.CreateTime = DateTime.Now;
                t_Form.FormID = formId;
                t_Form.Flag = "Join";

                t_Form.IsValid = 1;
                t_Form.UserId = join.UserId;
                _myDbContext.T_Form.Add(t_Form);

                T_PointsDetail t_Points = new T_PointsDetail();
                t_Points.UserId = join.UserId;
                t_Points.PointsRule = PointsRule.JOIN.ToString();
                _userService.AddPoints(t_Points);

                _myDbContext.SaveChanges();

             

                return model;

            }

            else
            {
                throw new Exception("活动不存在");
            }


        }

        public void SetHome(int userId, int activityId)
        {
            var user= _myDbContext.T_User.SingleOrDefault(i => i.Id == userId);
            if (user != null)
            {
                var model = _myDbContext.T_Activity.SingleOrDefault(i => i.Id == activityId);
                if (model != null)
                {
                    model.ExpireDate = user.ExpireDate;
                    model.IsHome = 1;
                    _myDbContext.SaveChanges();
                }
                else {
                    throw new Exception("活动不存在");

                }
            }
            else {
                throw new Exception ("用户不存在");
            }
        }

        public T_ActivityDetail Update(int id, string url)
        {
            var model = _myDbContext.T_ActivityDetail.SingleOrDefault(i => i.Id == id);
            var activity = _myDbContext.T_Activity.Single(i => i.Id == model.ActivityId);
            if (model.Index != null)
            {
                if (model.Index.Value == 0)
                {
                    activity.CoverPage = url;
                }
            }
            else
            {
                activity.CoverPage = "/images/default.png";
            }
            //var activity=_myDbContext.T_ActivityDetail.s

            model.Url = url;
            _myDbContext.SaveChanges();
            return model;
        }

        public void UpdateForm(string formId)
        {
            var model = _myDbContext.T_Form.First(i => i.FormID == formId || (DateTime.Now - i.CreateTime).Days > 7);
            model.IsValid = 1;
            _myDbContext.SaveChanges();
        }

        public T_Graphic UpdateGraphic(int id, string url)
        {
            var model = _myDbContext.T_Graphic.Single(i => i.Id == id);
            model.Img = url;
            _myDbContext.SaveChanges();
            return model;
        }

        public void UpdateOpen(int activityId,int isOpen)
        {
            var activity = _myDbContext.T_Activity.SingleOrDefault(i => i.Id == activityId);
            activity.IsOpen = isOpen;
            _myDbContext.SaveChanges();
        }

        /// <summary>
        /// 获取随机兑奖码
        /// </summary>
        /// <returns></returns>
        private string GetExchangeCode()
        {
            string chars = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

            Random randrom = new Random((int)DateTime.Now.Ticks);

            string str = "";
            for (int i = 0; i < 10; i++)
            {
                str += chars[randrom.Next(chars.Length)];
            }

            if (_myDbContext.T_Join.FirstOrDefault(i => i.ExchangeCode == str) != null) {
                str = GetExchangeCode();
            }
            return str;
        }
    }
}
